var async = require('async');
var AV = require('leanengine');
var config = require('../../config.js');
var AE = require("apiengine")({mode:config.dev,scope:'activity',adapter:'mysql'});
var Q = require('Q');
var SignDayGive = AV.Object.extend('ActivitySignDayGive');
var SignDayUser = AV.Object.extend('ActivitySignDayUser');
module.exports = {
    updateSignDayGive:function(uid){
        var q = Q.defer();
        async.waterfall([
            function(cb){
                var query = new AV.Query(SignDayGive);
                query.equalTo('Uid',uid);
                query.first().then(function(data){
                    if(data){
                        cb(null, data);
                    }else{
                        cb({code:-1});
                    }
                }).catch(function(err){
                    cb({code:-1});
                })
            },
            function(user,cb){
                var query = new AV.Query(SignDayGive);
                query.equalTo('Uid',uid);
                query.equalTo('RuleDays','D90');
                query.first().then(function(data){
                    if(data){
                        cb({code:-2})
                    }else{
                        cb(null, user)
                    }
                }).catch(function(err){
                    cb({code:-2})
                })
            },
            function(user,cb){
                var res = new SignDayGive();
                var new_info={
                    Uid:uid,
                    firstSignDate:user.get('firstSignDate'),
                    RuleDays:'D90',
                    Mold:'0',
                    Month:2,
                    Year:2,
                    GiveMold:1
                };
                res.save(new_info).then(function(data){
                    cb(null, {code:0});
                }).catch(function(err){
                    cb({code:-3})
                });
            }
        ],function(err,results){
            if(err){
                q.reject(err);
            }else{
                q.resolve(results);
            }
        });
        return q.promise ;
    },
    getInfo:function(){
        var q = Q.defer();
        var query =new AE.Query('gr_zsm_sign');
        //query.condition(' limit 0,100')
        query.find().then(function(data){
            //console.log(data.get('id'))
            if(data.get().length >0){
                q.resolve(data.get());
            }else{
                q.reject({code:-1});
            }
        });
        return q.promise ;
    }
}